<template>
	<view class="main position-relative animated fadeIn faster">
		<view class="px-5 d-flex d-flex-middle" :style="{'paddingTop':$store.state.statusBarHeight+'px','height': $store.state.titleBarHeight + 'px'}">
			
		</view>
		<view class="d-flex d-flex-column d-flex-center d-flex-middle" style="padding-top: 200rpx;">
			<image class="mb-10" src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/appUpload/20241223141109-ac38c1fa-47fb-46f8-83fc-1f37a1474265.png" style="width: 140rpx;height: 140rpx;"></image>
			<view class="mb-3" v-if="type==1">
				<view class="input-item d-flex d-flex-middle mb-3">
					<input v-model="phone" placeholder="请输入手机号码" type="number" placeholder-class="colorhold" />
				</view>
				<view class="input-item d-flex d-flex-between d-flex-middle">
					<input v-model="code" type="number" placeholder="短信验证码" placeholder-class="colorhold" />
					<view class="mr-3 text-right" @click="sendCode" :class="totalTime<60?'sending':'code-btn'">{{codeBtnText}}</view>
				</view>
			</view>
			
			<view class="mb-3" v-else>
				<view class="input-item d-flex d-flex-middle mb-3">
					<input v-model="accountName" placeholder="请输入账号" placeholder-class="colorhold" />
				</view>
				<view class="input-item d-flex d-flex-middle" style="position: relative;">
					<input v-model="password" placeholder="请输入密码" type="text"  :password="showPassword2" placeholder-class="colorhold" />
					<view @click="changetype(2)"  style="position: absolute;right: 20rpx;">
						<image v-if="showPassword2" 
							   src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250103093128.png" 
							   style="width: 35rpx;height: 35rpx;" />
						<image v-if="!showPassword2" 
							   src="https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/app/%E5%BE%AE%E4%BF%A1%E5%9B%BE%E7%89%87_20250103093138.png" 
							   style="width: 35rpx;height: 35rpx;" />
					</view>
				</view>
			</view>
			
			<view class="d-flex-center">
				<view class="d-flex d-flex-top mb-3">
					<checkbox :checked="isChecked" style="transform:scale(0.6)" @click="ChangeisChecked"></checkbox>
					<view>
						<text class="font24 color999" @click="ChangeisChecked">我已阅读并同意</text>
						<text class="font24 colorlan" @click="gotoUserAgreement">《用户协议》</text>
						<text class="font24 color999">和</text>
						<text class="font24 colorlan" @click="gotoPrivacyPolicy">《隐私条款》</text>
					</view>
				</view>
				<button class="wxbutton d-flex d-flex-middle d-flex-center" :style="inputStyles"  style="width: 600rpx;font-size: 36rpx;" @click="userLogin">登录</button>
				<view class="py-2 d-flex d-flex-center" @click="goApplePay">
					<text class="color999 font26">{{type=='1'?'账号密码登录':'手机验证码登录'}}</text>
				</view>
			</view>
		</view>
		
		<uni-popup ref="phonePopup" background-color="#fff" border-radius="8px 8px 8px 8px">
			<view class="popup-content changeNike" style="height: 350rpx;">
				<view class="text-center font32">手机号码</view>
				<input class="uni-input" maxlength="11" v-model="mobile" focus/>
				<view class="desc">请输入您的手机号码</view>
				<view class="btn d-flex position-absolute">
					<view class="cancle text-center font28" style="width: 50%; line-height: 90rpx; border-right: 1px solid #ededed;" @click="colsePhonePopup">取消</view>
					<view class="confirm text-center font28" style="width: 50%; line-height: 90rpx;" @click="confirmPhone">确认</view>
				</view>
			</view>
		</uni-popup>
		
		<view class="position-fixed top-0 left-0 right-0 bottom-0" style="background: rgba(0, 0, 0, .4);" v-if="showAgreePopup">
			<view class="position-relative bg-fff rounded20 pt-4 px-4 pb-2" style="top: 50%; left: 50%; transform: translate(-50%, -50%); width: 550rpx; overflow: hidden;">
				<view class="font-bold font32 mb-2 text-center">用户协议及隐私政策</view>
				<view class="mb-4">
					已阅读并同意
					<text style="color: #1ac2ff;" @click="gotoUserAgreement">《用户协议》</text>和<text style="color: #1ac2ff;" @click="gotoPrivacyPolicy">《隐私条款》</text>
					，运营商将对你提供的手机号进行验证
				</view>
				<view class="w-100 py-3 rounded10 colorfff text-center" style="background: #1ac2ff;" @click="ChangeAgree(true)">同意</view>
				<view class="w-100 py-2 text-center" @click="ChangeAgree(false)">不同意</view>
			</view>
		</view>
	</view>
</template>

<script>
	import store from '@/store/index.js';
	import { manner } from "@/util/manner.js";
	import { userApi } from '@/http/userApi.js';
	import { USER_TOKEN,REFRESH_TOKEN,FIRST_LOGIN } from '@/constants/local-storage-key-const';
	// https://blog.csdn.net/happyisland1988/article/details/147224075
	// https://yr7ywq.smartapps.baidu.com/?_chatQuery=uniapp%20ios%20%E6%94%AF%E4%BB%98&searchid=86765d3a0000928e&_chatParams=%7B%22agent_id%22%3A%22c816%22%2C%22content_build_id%22%3A%2210b7382b%22%2C%22from%22%3A%22q2c%22%2C%22token%22%3A%22UGlGZHdpN0lzYXNVbS9Gb1JoeVNNWXRmOGI3Q0R2VFNVZlJSWlMzOW9SSnBLMlZCSGVMZEFwcDkwZVZIUEFKejRlMnhXMUQvamxvZVRuOVVRMWR4TzczVHFaVm9ENVZVajNPMjg4dkNMRTNVUXRYaGZFaW14dW5kN1ZlR1o0RGo%3D%22%2C%22chat_no_login%22%3Atrue%7D&_swebScene=3711000610001000
	export default {
		data() {
			return {
				isChecked: false,
				showAgreePopup: false,
				totalTime: 60,
				timer: null,
				codeBtnText: '发送验证码',
				accountName:'',
				clientId:'',
				phone:'',
				password:'',
				code:'',
				showPassword2: true,
				type:'3',
				mobile:''
			}
		},
		onLoad() {
			let that = this
			uni.getPushClientId({
			  success(res) {
				that.clientId = res.cid
				console.log('clientId:',that.clientId);
			  },
			  fail(err) {
			    console.log('err',err)
			  }
			})
		},
		methods: {
			changType(){
				this.accountName = ''
				this.password = ''
				this.phone = ''
				this.code = ''
				if(this.type == '1'){
					this.type = '3'
				}else{
					this.type = '1'
				}
			},
			ChangeAgree(flag) {
				this.isChecked = flag
				this.showAgreePopup = false
			},
			async confirmPhone(){
				let that = this;
				if(that.mobile.length !== 11){
					uni.showToast({
						title:'请输入正确手机号',
						icon:'none',
					})
					return
				}
				try {
					uni.showLoading({
						title:'加载中...'
					})
					await userApi.editUserInfo({'phone':that.mobile})
					uni.hideLoading()
					that.$refs.phonePopup.close()
					uni.navigateTo({
						url: '/pagesMain/Initial-info/Initial-info',
					})
				} catch (error) {
					uni.hideLoading()
					console.log('error',error)
				}
			},
			colsePhonePopup(){
				this.$refs.phonePopup.close()
			},
			changetype(index) {
				
				if (index === 2) {
					this.showPassword2 = !this.showPassword2;
				}
			},
			wxlogin(){
				uni.navigateTo({
					url:'/pagesMain/login/login'
				})
			},
			gotoPrivacyPolicy() {
				uni.navigateTo({
					url:'/pagesMain/privacy/privacy?type=1'
					// url: '/pagesMain/PrivacyPolicy/PrivacyPolicy'
				})
			},
			gotoUserAgreement() {
				uni.navigateTo({
					url:'/pagesMain/privacy/privacy?type=2'
					// url: '/pagesMain/UserAgreement/UserAgreement'
				})
			},
			privacy(){
				uni.navigateTo({
					url:'/pagesMain/privacy/privacy'
					// url:'/pagesMain/hobby/hobby'
				})
			},
			goBack(){
				manner.goBack()
			},
			fastLogin(){
				let that = this
				uni.login({
					provider:'univerify',
					univerifyStyle:{
						fullScreen:false,
						"backgroundImage": "https://yuexiaoda-1314351529.cos.ap-shanghai.myqcloud.com/formal/images/bootbg.png",
						"icon": {
						    "path": "static/images/logo.png",
						    "width":  "60px",
						    "height": "60px"
						},
						"phoneNum": {
						    "color": "#202020"
						},
						"slogan": {
						    "color": "#BBBBBB"
						},
						"authButton": {
						    "normalColor": "#c2edf4",
						    "highlightColor": "#1ac2ff",
						    "disabledColor": "#dce0df",
						    "textColor": "#ffffff",
						    "title": "本机号码一键登录",
						    "borderRadius": "24px"
						},
						"otherLoginButton": {
							"visible": false
						},
						"privacyTerms": {
						    "defaultCheckBoxState":true,
						    "isCenterHint":false,
						    "checkBoxSize":12,
							"checkedImage":"static/images/checkbox-checked.png",
							"uncheckedImage":"static/images/checkbox.png",
						    "textColor": "#BBBBBB",
						    "termsColor": "#43abe5",
						    "prefix": "我已阅读并同意",
						    "suffix": "并使用本机号码登录"
						},
					},
					success:res=>{
						let openid = res.authResult.openid;
						let access_token = res.authResult.access_token;
						uniCloud.callFunction({
							name: "getPhoneNumber",
							data: {
								openid,
								access_token
							},
						}).then(res1 => {
							let phoneNumber = res1.result.phoneNumber;
							that.getLoginInfo({'phone':phoneNumber,'type':'6','clientId':that.clientId},true)
						}).catch((err) => {
							uni.showToast({
								title:'手机号一键登录失败！',
								icon:'none'
							})
							console.log('手机号获取失败！',err)
						})
					},fail(err) {
						console.log('err',err)
					}
				})
			},
			ChangeisChecked() {
				console.log(this.isChecked);
				if(!this.isChecked) {
					this.showAgreePopup = true
				} else {
					this.isChecked = false
				}
			},
			async sendCode(){
				let that = this
				if(that.phone.length !== 11){
					uni.showToast({
						title:'请输入正确的手机号码',
						icon:'none',
					})
					return
					
				}
				if(that.totalTime == 60){
					try{
						uni.showLoading({
							title:'发送中'
						})
						let res=await userApi.sendCode(that.phone)
						console.log(res);
						uni.hideLoading()
						that.startTimer()
					}catch(e){
						uni.hideLoading()
						console.log('error',e)
					}
				}
			},
			async userLogin(){
				let that = this
				let formData = {}
				if(that.type == '1'){
					if(that.phone.length != 11){
						uni.showToast({
							title:'请输入正确的手机号码',
							icon:'none',
						})
						return
					}
					if(that.code == ''){
						uni.showToast({
							title:'请输入短信验证码',
							icon:'none',
						})
						return
					}
					formData = {
						'phone':that.phone,
						'code':that.code,
						'clientId':that.clientId,
						'type':that.type
					}
				}else{
					if(that.accountName == ''){
						uni.showToast({
							title:'请输入账号',
							icon:'none',
						})
						return
					}
					if(that.password == ''){
						uni.showToast({
							title:'请输入密码',
							icon:'none',
						})
						return
					}
					formData = {
						'accountName':that.accountName,
						'password':that.password,
						'clientId':that.clientId,
						'type':that.type
					}
				}
				if(!that.isChecked){
					this.showAgreePopup = true
					return
				}
				uni.showLoading({
					title:'登录中'
				})
				try{
					let udata = await userApi.userLogin(formData)
					uni.hideLoading()
					uni.setStorageSync(USER_TOKEN, udata.accessToken)
					uni.setStorageSync(REFRESH_TOKEN, udata.refreshToken)
					store.commit('setLogin',udata.userAccountVo)
					this.imLogin(udata.userAccountVo.uid,udata.imSign)
					if(!udata.userAccountVo.gender){
						uni.navigateTo({
							url: '/pagesMain/Initial-info/Initial-info',
						})
					}else{
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}catch(e){
					uni.hideLoading()
				}
			},
			async getLoginInfo(formData,bl=false){
				uni.showLoading({
					title:'登录中...'
				})
				console.log('formData入参',formData)
				try{
					let udata = await userApi.userLogin(formData)
					console.log('udata',udata)
					uni.hideLoading()
					uni.setStorageSync(USER_TOKEN, udata.accessToken)
					uni.setStorageSync(REFRESH_TOKEN, udata.refreshToken)
					store.commit('setLogin',udata.userAccountVo)
					this.imLogin(udata.userAccountVo.id,udata.imSign)
					if(bl){
						uni.closeAuthView()
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
					if(!udata.userAccountVo.phone){
						this.$refs.phonePopup.open()
						return
					}
					if(!udata.userAccountVo.gender){
						uni.navigateTo({
							url: '/pagesMain/Initial-info/Initial-info',
						})
					}else{
						uni.switchTab({
							url: '/pages/index/index'
						})
					}
				}catch(e){
					uni.hideLoading()
					if(bl){
						uni.closeAuthView()
					}
				}
			},
			imLogin(uid,ims){
				let getlogin = this.$tim.login({
					userID:uid,
					userSig:ims
				});
				getlogin.then(function(imResponse) {
					if (imResponse.data.repeatLogin === true) {
						console.log('imResponse.data.errorInfo',imResponse.data.errorInfo);
					} else {}
				}).catch(function(imError) {
					console.warn('重复登录', imError);
				});
			},
			startTimer() {
				if (this.timer) return;
				this.totalTime--;
				this.codeBtnText = `${this.totalTime}s后发送`;
				this.timer = setInterval(() => {
				    if (this.totalTime <= 0) {
				        clearInterval(this.timer);
				        this.timer = null;
				        this.codeBtnText = '发送验证码';
						this.totalTime = 60
				    } else {
				        this.totalTime--;
				        this.codeBtnText = `${this.totalTime}s后发送`;
				    }
				}, 1000);
			},
			wxLoginApp(){
				// #ifdef APP-PLUS
				let that = this
				uni.getProvider({
					service: 'oauth',
					success: function(res) {
						if (~res.provider.indexOf('weixin')) {
							uni.login({
								provider: 'weixin',
								success: function(loginRes) {
									uni.getUserInfo({
								        provider: 'weixin',
										onlyAuthorize: true,
								        success: function(infoRes) {
											console.log('infoRes',infoRes)
											infoRes.clientId = that.clientId
											let userInfo = JSON.stringify(infoRes.userInfo)
											let type = '4'
											that.getLoginInfo({userInfo,type},false)
										},
										fail:function(err){
											uni.showToast({
												title:'微信授权登录失败！',
												icon:'none'
											})
										}
								    });
								},
								fail:function(err){
									console.log('err',err)
									uni.showToast({
										title:'微信授权登录失败！！',
										icon:'none'
									})
								}
							})
						}
					},
					fail:function(e){
						uni.showToast({
							title:'微信授权登录失败！！！',
							icon:'none'
						})
					}
				})
			    // #endif
			},
			qqLoginApp(){
				let that = this
				uni.login({
				    provider: 'qq',
				    success: function(loginRes) {
				        const openid = loginRes.authResult.openid;
				        uni.getUserInfo({
				            provider: 'qq',
				            success: function(infoRes) {
								console.log('userInfo',infoRes.userInfo)
				                let formdata = {
				                    nickName: infoRes.userInfo.nickname,
				                    gender: infoRes.userInfo.gender == '男' ? 1 : 2,
				                    headImgUrl: infoRes.userInfo.figureurl_qq_2,
				                    openId: openid,
									clientId : that.clientId
				                };
								let userInfo = JSON.stringify(formdata)
								let type = '5'
								
								that.getLoginInfo({userInfo,type},false)
				            },
				            fail: function(err) {
				                uni.showToast({
				                    title: '获取用户信息失败',
				                    icon: 'none',
				                    duration: 3000
				                });
				            }
				        });
				    },
				    fail: function(err) {
				        // 登录授权失败处理
				        uni.showToast({
				            title: '登录授权失败',
				            icon: 'none',
				            duration: 3000
				        });
				    }
				});

			},
			noAction(){
				console.log('aaaaa')
				this.$refs.phonePopup.open()
				// uni.showToast({
				// 	title:'该功能暂未开启',
				// 	icon:'none'
				// })
			},
			goUrlTest(){
				uni.navigateTo({
					url:'/pagesMain/Initial-info/Initial-info'
				})
			}
		},
	
	 computed: {
	    inputStyles() {
	      // 检查每个字段是否有值
	      const hasPhone = this.phone.trim() !== '';
	      const hasCode = this.code.trim() !== '';
	      const hasAccountName = this.accountName.trim() !== '';
	      const hasPassword = this.password.trim() !== '';
			if(hasPhone && hasCode||hasAccountName && hasPassword){//有值时
				return {
				        backgroundColor:'#1ac2ff !important'
				      };
			}else{
				return {
				    backgroundColor:'#c2edf4 !important'
				};
			}
	     
	    }
	  },
	}
	
</script>

<style scoped lang="scss">
.input-item{
	width: 550rpx;
	height: 94rpx;
	border: solid 1px #dcdcdf;
	border-radius: 60rpx;
	background-color: #ffffff;
	padding-left: 50rpx;
}
.colorlan {color: #1ac2ff;}
.code-btn{color: #1ac2ff;width: 180rpx;}
.sending{color:#999;width: 180rpx;}
.changeNike {
	padding: 40rpx 60rpx 0;
	color: #1f1f1f;
	input {
		box-sizing: border-box;
		border-radius: 10rpx;
		color: #333333;
		font-size: 26rpx;
		width: 100%;
		margin-top: 50rpx;
		height: 70rpx;
		padding-left: 20rpx;
		background-color: #efefef;
	}
	.desc {
		margin-top: 20rpx;
		font-size: 22rpx;
		color: #888888;
	}
	.btn {
		bottom: 0;
		left: 0;
		width: 100%;
		height: 90rpx;
		border-top: 1px solid #ededed;
	}
	.cancle {
		color: #9E9D9D;
	}
	.confirm {
		color: #66CCCC;
	}
}
</style>